package actions;

import io.GPSPoint;
import io.GPXFileParser;
import io.SimpleParser;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Loads files and fires as {@link Settings#LOADED_GPS_FILES} event when done
 * 
 * @author oliver 
 */
public class LoadGPSFilesAction implements PropertyChangeListener {

	public LoadGPSFilesAction() {
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(Settings.getInstance().LOAD_GPS_FILES)) {
			FileChooser fc = (FileChooser) evt.getNewValue();
			File[] files = fc.getFiles();
			Map<String, List<GPSPoint>> gpsPoints = new HashMap<String, List<GPSPoint>>();
			for (File file : files) {
				List<GPSPoint> p = null;
				try {
					if (file.getName().endsWith(".gps")) {
						p = SimpleParser.parseFile(file);
					} else if (file.getName().endsWith(".gpx")) {
						p = GPXFileParser.parseFile(file);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (fc.isSetStartTimeZero()) {
					if (p != null) {
						List<GPSPoint> p2 = new ArrayList<GPSPoint>();
						long start = p.get(0).getTime();
						for (GPSPoint gpsPoint : p) {
							long time = gpsPoint.getTime();
							gpsPoint.setTime(time - start);
							p2.add(gpsPoint);
						}
						gpsPoints.put(file.getName(), p2);
					}
				} else {
					if (p != null) {
						gpsPoints.put(file.getName(), p);
					}
				}
			}
			Settings.getInstance().getPropertyChangeSupport().firePropertyChange(Settings.LOADED_GPS_FILES, null, gpsPoints);
		}
	}


}
